/**
 * 
 */
package com.netflexitysolutions.amazonws.sdb.internal.operations;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.amazonaws.sdb.doc._2009_04_15.PutAttributes;
import com.amazonaws.sdb.doc._2009_04_15.PutAttributesResponse;
import com.amazonaws.sdb.doc._2009_04_15.ReplaceableAttribute;
import com.amazonaws.sdb.doc._2009_04_15.ResponseMetadata;
import com.netflexitysolutions.amazonws.sdb.Domain;
import com.netflexitysolutions.amazonws.sdb.Item;
import com.netflexitysolutions.amazonws.sdb.ItemAttribute;
import com.netflexitysolutions.amazonws.sdb.SimpleDB;
import com.netflexitysolutions.amazonws.sdb.Statistics;

/**
 * @author netflexity
 *
 */
public class PutAttributesOperation extends OperationExecutor<PutAttributes, Void>{
	
	private String domainName;
	private String id;
	private List<ItemAttribute> attributes;
	
	/**
	 * @param simpleDB
	 * @param domain
	 * @param item
	 */
	public PutAttributesOperation(SimpleDB simpleDB, Domain domain, Item item) {
		super(simpleDB);
		
		this.domainName = domain.getName();
		assert(StringUtils.isNotBlank(this.domainName));
		
		this.id = item.getIdentifier();
		assert(StringUtils.isNotBlank(this.id));
		
		this.attributes = item.getAttributes();
	}
	
	/* (non-Javadoc)
	 * @see com.netflexitysolutions.amazonws.sdb.internal.OperationExecutor#call(java.lang.Object)
	 */
	@Override
	protected Void call(PutAttributes request){
		// Prepare request.
		request.setDomainName(domainName);
		request.setItemName(id);
		
		// See if we got any attribute names.
		if(attributes != null){
			for (ItemAttribute attr : attributes) {
				List<String> values = attr.getValues();
				if(!values.isEmpty()){
					ReplaceableAttribute replacableAttr = new ReplaceableAttribute();
					replacableAttr.setName(attr.getName());
					replacableAttr.setValue(attr.getValue());
					replacableAttr.setReplace(attr.isReplace());
					request.getAttribute().add(replacableAttr);
					
					// For attributes with multiple values.
					if(values.size() > 1){
						for (int i = 1; (i < values.size() && i < 256); i++) {
							replacableAttr = new ReplaceableAttribute();
							replacableAttr.setName(attr.getName());
							replacableAttr.setValue(values.get(i));
							replacableAttr.setReplace(false);
							request.getAttribute().add(replacableAttr);
						}
					}
				}
			}
		}
		
		// Invoke operation.
		PutAttributesResponse response = getSimpleDB().getService().putAttributes(request);
		if(response != null){
			ResponseMetadata metadata = response.getResponseMetadata();
			if(metadata != null){
				this.stats = new Statistics(metadata.getRequestId(), metadata.getBoxUsage());
			}
		}
		return null;
	}
}
